package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.system.domain.RescueData;
import com.ruoyi.system.domain.TipsData;
import com.ruoyi.system.service.IOpenService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class OpenServiceImpl implements IOpenService {
    @Resource
    private RedisCache redisCache;
    @Value("${open.appKey}")
    private String appKey;
    @Value("${open.url}")
    private String openUrl;
    @Value("${open.appSecret}")
    private String appSecret;
    @Override
    public String getToken() {
        String timestamp = getTimestamp();
        String signature ="&action=token&appKey="+appKey+"&appSecret="+appSecret+"&timestamp="+timestamp+"&";
        String url = openUrl + "scdeap/api/elenfc/getEleNfcToken?action=token&appKey="+appKey+"&appSecret="+appSecret+"&timestamp="+timestamp+"&sign="+ Md5Utils.hash(signature).toUpperCase();
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<JSONObject> httpEntity = new HttpEntity<>(null);
        ResponseEntity<String> result = restTemplate.postForEntity(url,httpEntity,String.class);
        JSONObject jsonObject= JSONObject.parseObject(result.getBody());
        if(jsonObject.getString("code").equals("200")){
            JSONArray data = jsonObject.getJSONArray("data");
            JSONObject tokenObject = data.getJSONObject(0);
            redisCache.setCacheObject("openToken",tokenObject.getString("token") , 120, TimeUnit.MINUTES);
            return tokenObject.getString("token");
        }else{
            return null;
        }
    }

    @Override
    public List<TipsData> getRescueData() {
        String token= redisCache.getCacheObject("openToken");
        if(token==null)
        {
            token=getToken();
        }
        JSONObject jsonObject = getContent("EleEquDown",token);
        JSONObject data=new JSONObject();
        jsonObject.put("data",data);
        String url = openUrl + "scdeap/api/elenfc/getEleNfcDeviceData";

        JSONObject result = HttpUtils.sendPostJSONData(url, jsonObject,token);
        if(result.getString("code").equals("200")){
            JSONArray dataResult = result.getJSONArray("data");
            List<TipsData> tipsDataList = dataResult.toJavaList(TipsData.class);
            return tipsDataList;
        }
        return null;
    }

    @Override
    public String setRescueData(RescueData rescueData) {
        String token= redisCache.getCacheObject("openToken");
        if(token==null)
        {
            token=getToken();
        }
        JSONObject jData= getDetail(rescueData.getSBZCDM());
        JSONArray jsonArray=jData.getJSONArray("data");
        if(jsonArray.isEmpty())
        {
            return null;
        }

        JSONObject jsonObject =getContent("EleNfcIdUpload",token);
        JSONObject data=new JSONObject();
        data.put("sbzcdm",rescueData.getSBZCDM());
        data.put("nfcid",rescueData.getNFCID());
        jsonObject.put("data",data);
        String url = openUrl + "scdeap/api/elenfc/eleNfcIdUpload";
        JSONObject result = HttpUtils.sendPostJSONData(url, jsonObject,token);
        if(result.getString("code").equals("200")){
            return result.getString("message");
        }
        return null;
    }
    @Override
    public  JSONObject getDetail(String sbzcdm)
    {
        String token= redisCache.getCacheObject("openToken");
        if(token==null)
        {
            token=getToken();
        }
        JSONObject jsonObject =getContent("getEleNfcDeviceInfo",token);
        JSONObject data=new JSONObject();
        data.put("sbzcdm",sbzcdm);
        jsonObject.put("data",data);
        String url = openUrl + "scdeap/api/elenfc/getEleNfcDeviceInfo";
        JSONObject result = HttpUtils.sendPostJSONData(url, jsonObject,token);
        if(result.getString("code").equals("200")){
            return result;
        }
        return null;
    }
    /**
     * 获取content
     */
    public JSONObject getContent(String action,String token) {
        String timestamp = getTimestamp();
        String signature = Md5Utils.hash("&action="+action+"&timestamp=" + timestamp + "&"+"token="+token+"&").toUpperCase();
        JSONObject jsonObject = new JSONObject();
        JSONObject content = new JSONObject();
        content.put("version", "1.0");
        content.put("timestamp", timestamp);
        content.put("signature", signature);
        jsonObject.put("context", content);
        return jsonObject;
    }
    /**
     * 获取时间戳
     * @return
     */
    public String getTimestamp() {
        LocalDateTime now = LocalDateTime.now();
        // 定义日期时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd HHmmss");
        // 格式化日期时间
        String formattedDateTime = now.format(formatter);
        return formattedDateTime.replace(" ", "T");
    }
}
